#include <xmllite.h>
#include <gdiplus.h>
#pragma comment (lib, "XmlLite.lib")
#pragma comment (lib, "Gdiplus.lib")

#include <iostream>
#include <fstream>

#include "Setting.h"
#include "Page.h"
#include "Miscellaneous.h"

using namespace std;
using namespace Gdiplus;

shared_ptr<CSetting> CSetting::_instance;
CSetting::CSetting(const wchar_t* settingFile) throw(...)
{
	GdiplusStartupInput gdiplusStartupInput;
	// Initialize GDI+.
	GdiplusStartup(&_token, &gdiplusStartupInput, NULL);	

	// Initialize setting
	InitSettingFromFile(settingFile);
}


CSetting::~CSetting(void)
{
	GdiplusShutdown(_token);
}

void CSetting::InitSettingFromFile(const wchar_t* settingFile) throw(...)
{
	HRESULT hr;
	CComPtr<IStream> pFileStream;
	CComPtr<IXmlReader> pReader;
	XmlNodeType nodeType;

	//
	if (FAILED(hr = SHCreateStreamOnFile(settingFile, STGM_READ, &pFileStream))) {
		throw wstring(L"Error creating file reader, File->") + settingFile;
	}

	if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL))) {
		throw wstring(L"Error creating xml reader");
	}

	if (FAILED(hr = pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit))) {
		throw wstring(L"Error setting XmlReaderProperty_DtdProcessing");
	}

	if (FAILED(hr = pReader->SetInput(pFileStream))) {
		throw wstring(L"Error setting input for reader");
	}

	// read until there are no more nodes
	while (S_OK == (hr = pReader->Read(&nodeType))) {
		switch (nodeType) {

		case XmlNodeType_Element:
			{
				if(CMiscellaneous::GetLocalName(pReader) == L"html")
					_vp.push_back(unique_ptr<CPage>(new CPage(pReader)));
			}
			break;
		}
	}

	//
}

shared_ptr<CSetting> CSetting::Current() throw(...)
{
	if(!_instance)
	{
		_instance.reset(new CSetting(CMiscellaneous::GetSettingFile().c_str()));
	}
	return _instance;
}

const vector<unique_ptr<CPage>>* CSetting::GetPages() const throw()
{
	return &_vp;
}



